package com.hubu.thread.pattern;
import java.util.ArrayList;
import java.util.List;
/**
 *
 *
 * 保护性暂停模式 一个线程等待其他线程的结果
 */
public class GuardedObject {
    private Object result;
    public Object get(){
        synchronized (this){
            while(result==null){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    }

    public Object get(long mills){
        long timePass=0;//已经等待的时间
        synchronized (this){
            while(result==null){

                long begin=System.currentTimeMillis();
                long waitTime=mills-timePass;
                //如果已经达到mills
                if(waitTime<=0){
                    break;
                }
                try {
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                timePass=System.currentTimeMillis()-begin;
                System.out.println("timePass="+timePass);
            }
        }
        System.out.println("停止等待");
        return result;
    }
    public void complete(Object result){
        synchronized (this){
            this.result=result;
            this.notifyAll();
        }
    }
    public static void main(String[] args) {
        GuardedObject guardedObject=new GuardedObject();
        Thread t1=new Thread(()->{
            try {
                Thread.sleep(5000);
                List<String> result=new ArrayList<>();
                result.add("hello world");
                result.add("world,hello");
                guardedObject.complete(result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2=new Thread(()->{
            Object o = guardedObject.get(1000);
            System.out.println(o);
        });
        t1.start();
        t2.start();
    }
}